package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.PrivateChannelRefreshAdapter;
import com.jdy.haoduoai.adapter.PrivateChannelRefreshAdapter.OnChangeCallback;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.LePrivateChannelItem;
import com.jdy.haoduoai.model.LePrivateChannelList;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.PrivateChannelMenuItemVo;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.pulltorefresh.PullableListView;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import rx.Observable;
import rx.android.observables.AndroidObservable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.functions.Func2;
import rx.schedulers.Schedulers;

//import com.jdy.haoduoai.R;

/**
 * 专属频道
 * 
 * @author Administrator
 * 
 */
public class PrivatechannelActivity extends BaseActivity implements
        OnRefreshListener, OnChangeCallback {

  @InjectView(id = R.id.content_views)
  private PullableListView listview;
  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.emptylayout)
  private LinearLayout emptylayout;
  @InjectView(id = R.id.reloadRippleView)
  private RippleView reloadRippleView;

  private PrivateChannelRefreshAdapter adapter;
  private ArrayList<PrivateChannelMenuItemVo> mList;
  private LeUser mLeUser;
  private String lastTags;
  String xml = "";

  private ACache mCache;

  private LePrivateChannelList mLePrivateChannelList;
  private HashMap<String, Object> channelMap;

  // 大类： [吃饭, 学习]
  private ArrayList<String> selectedCategoryKey = new ArrayList<String>();

  // {学习=[不爱学习, 上学哭闹], 吃饭=[挑食偏食, 边吃边玩, 爱吃零食]}
  private HashMap<String, ArrayList<String>> channelKeyValueMap = new HashMap<String, ArrayList<String>>();

  private int totalMonth;

  /**
   * 判断宝宝年龄
   */
  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null && Tools.isNotEmpty(lu.machine)) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

      try {
        Calendar bef = Calendar.getInstance();
        bef.setTime(sdf.parse(lu.machine.dob));

        int month = Calendar.getInstance().get(Calendar.MONTH)
            - bef.get(Calendar.MONTH);

        int year = Calendar.getInstance().get(Calendar.YEAR)
            - bef.get(Calendar.YEAR);

        totalMonth = year * 12 + month;
        if (totalMonth == 0) {
          totalMonth = 1;
        }

      } catch (Exception e) {
        // TODO: handle exception
      }
    }
  }

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.privatechannel);
    setTitle("专属频道");

    showloading("");

    checkBabyAge();

    getbtn_right().setVisibility(View.GONE);
    mTvUpright.setVisibility(View.VISIBLE);
    mTvUpright.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {

        if (totalMonth >= (6 * 12)) {
          // Intent t = new Intent(PrivatechannelActivity.this,
          // AttractNewRepelActivity.class);
          // startActivity(t);
        } else {
          startActivity(new Intent(PrivatechannelActivity.this,
              AbilityTestActivity.class));
        }

        finish();
      }
    });

    initialize();
    initListener();
    requestData();
  }

  @SuppressWarnings("unchecked")
  private void initialize() {
    mCache = ACache.get(this);
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mList = new ArrayList<PrivateChannelMenuItemVo>();
    lastTags = LePreference.getInstance().getString("interesttags");

    channelMap = (HashMap<String, Object>) LeXiaoXiaoBanApp.globalMeta
        .get("privateChannelCategory");

    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }

    if (Tools.isNotEmpty(mLeUser.tags) && channelMap != null) {

      String[] str = mLeUser.tags.split(";");

      Set<Entry<String, Object>> entrys = channelMap.entrySet();
      Iterator<Entry<String, Object>> itrator = entrys.iterator();
      while (itrator.hasNext()) {
        Entry<String, Object> entryc = itrator.next();

        List<String> vlist = (List<String>) entryc.getValue();
        for (int i = 0; i < str.length; i++) {
          if (vlist.contains(str[i])) {
            if (channelKeyValueMap.containsKey(entryc.getKey())) {
              channelKeyValueMap.get(entryc.getKey()).add(str[i]);
            } else {
              ArrayList<String> val = new ArrayList<String>();
              val.add(str[i]);
              channelKeyValueMap.put(entryc.getKey(), val);
            }

            if (!selectedCategoryKey.contains(entryc.getKey())) {
              selectedCategoryKey.add(entryc.getKey());
            }
          }
        }

      }
      // List<String> nameList = (List<String>) map.get(opPassenger
      // .getPassengertypename());
    }
  }

  private void initListener() {
    reloadRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            new GetDataTask().execute();
          }
        });

    pullToRefreshLayout.setOnRefreshListener(this);
  }

  /**
   * 
   * @param key
   *          吃饭、情绪、睡觉等
   * @param tags
   *          二级标签
   */
  private void loadPrivateChannel(final String key, final String tags) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, final ResponseResult result) {
        if (result.isSuccess() && Tools.isNotNullStr(result.data)) {
          new Thread() {
            @Override
            public void run() {
              mCache.remove(key);
              mCache.put(key, result.data);
            }
          }.start();

          mLePrivateChannelList = JsonSerializer.getInstance().deserialize(
              result.data, LePrivateChannelList.class);

          if (mLePrivateChannelList != null
              && mLePrivateChannelList.data != null
              && !mLePrivateChannelList.data.isEmpty()) {

            PrivateChannelMenuItemVo itemVo = new PrivateChannelMenuItemVo();

            itemVo.id = ""; // );
            itemVo.name = key;

            String drawableStr = "drawable://";
            switch (key) {
            case "吃饭":
              drawableStr += R.drawable.eaticon;
              break;
            case "情绪":
              drawableStr += R.drawable.moodicon;
              break;
            case "社交":
              drawableStr += R.drawable.gamicon;
              break;
            case "性格":
              drawableStr += R.drawable.natureicon;
              break;
            case "学习":
              drawableStr += R.drawable.readicon;
              break;
            case "洗漱":
              drawableStr += R.drawable.washicon;
              break;
            case "睡眠":
              drawableStr += R.drawable.sleepicon;
              break;

            default:
              break;
            }

            itemVo.imgurl = drawableStr; // );
            itemVo.list = (ArrayList<LePrivateChannelItem>) mLePrivateChannelList.data;

            // 每次更新，换一换先删除旧的
            int index = 0;
            for (int i = 0; i < mList.size(); i++) {
              PrivateChannelMenuItemVo item = mList.get(i);
              if (item.name.contains(key)) {
                mList.remove(i);
                index = i;
                break;
              }
            }

            mList.add(index, itemVo);

            setAdapter();

          }

        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_TAG_I, tags.trim().replaceAll(" ", ""));
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/episode", param_, HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void requestData() {
    loadChannelData();
    // for (String iKey : selectedCategoryKey) {
    // channelKeyValueMap.get(iKey);
    //
    // String labelStr = "";
    // if (channelKeyValueMap.get(iKey) != null
    // && !channelKeyValueMap.get(iKey).isEmpty()) {
    // for (String val : channelKeyValueMap.get(iKey)) {
    // labelStr += val + ";";
    // }
    // }
    //
    // // 获取对应大类下的子类内容
    // if (Tools.isNotEmpty(labelStr)) {
    // labelStr = labelStr.substring(0, labelStr.length() - 1);
    // loadPrivateChannel(iKey, labelStr);
    // }
    // }
  }

  private void loadChannelData() {
    Async.start(new Func0<ArrayList<String>>() {
      @Override
      public ArrayList<String> call() {
        return selectedCategoryKey;
      }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        .filter(new Func1<ArrayList<String>, Boolean>() {
          @Override
          public Boolean call(ArrayList<String> arg0) {
            return arg0 != null && !arg0.isEmpty();
          }
        }).flatMap(new Func1<ArrayList<String>, Observable<String>>() {
          @Override
          public Observable<String> call(ArrayList<String> selKeyList) {
            return AndroidObservable.bindActivity(PrivatechannelActivity.this,
                Observable.from(selKeyList));
          }
        }).flatMap(new Func1<String, Observable<ResponseResult>>() {
          @Override
          public Observable<ResponseResult> call(final String iKey) {
            return Async.start(new Func0<ResponseResult>() {
              @Override
              public ResponseResult call() {
                String cached = mCache.getAsString(iKey);

                if (Tools.isEmpty(cached) || lastTags == null
                    || mLeUser != null
                    && !mLeUser.tags.equalsIgnoreCase(lastTags)) {
                  String labelStr = "";
                  if (channelKeyValueMap.get(iKey) != null
                      && !channelKeyValueMap.get(iKey).isEmpty()) {
                    for (String val : channelKeyValueMap.get(iKey)) {
                      labelStr += val + ";";
                    }
                  }

                  if (Tools.isNotEmpty(labelStr)) {
                    labelStr = labelStr.substring(0, labelStr.length() - 1);
                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                    param_.put(HttpUtils.TAG_TAG_I,
                        labelStr.trim().replaceAll(" ", ""));
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    return HttpUtils.startRequest(HttpUtils.API_URL
                        + "/api/2.0/catalog/episode", param_,
                        HttpUtils.TAG_GET_REQUEST);
                  } else {
                    return null;
                  }
                } else {
                  ResponseResult r = new ResponseResult(1, cached, 1);
                  return r;
                }
              }
            }).filter(new Func1<ResponseResult, Boolean>() {
              @Override
              public Boolean call(ResponseResult returnResult) {
                return returnResult != null && returnResult.isSuccess();
              }
            });
          }
        }, new Func2<String, ResponseResult, Void>() {
          @Override
          public Void call(final String iKey, final ResponseResult result) {

            new Thread() {
              @Override
              public void run() {
                mCache.remove(iKey);
                mCache.put(iKey, result.data);
              }
            }.start();

            mLePrivateChannelList = JsonSerializer.getInstance().deserialize(
                result.data, LePrivateChannelList.class);

            if (mLePrivateChannelList != null
                && mLePrivateChannelList.data != null
                && !mLePrivateChannelList.data.isEmpty()) {

              PrivateChannelMenuItemVo itemVo = new PrivateChannelMenuItemVo();

              itemVo.id = ""; // );
              itemVo.name = iKey; // );

              String drawableStr = "drawable://";
              switch (iKey) {
              case "吃饭":
                drawableStr += R.drawable.eaticon;
                break;
              case "情绪":
                drawableStr += R.drawable.moodicon;
                break;
              case "社交":
                drawableStr += R.drawable.gamicon;
                break;
              case "性格":
                drawableStr += R.drawable.natureicon;
                break;
              case "学习":
                drawableStr += R.drawable.readicon;
                break;
              case "洗漱":
                drawableStr += R.drawable.washicon;
                break;
              case "睡眠":
                drawableStr += R.drawable.sleepicon;
                break;

              default:
                break;
              }

              itemVo.imgurl = drawableStr; // );
              itemVo.list = (ArrayList<LePrivateChannelItem>) mLePrivateChannelList.data;

              mList.add(itemVo);

            }

            return null;
          }
        }, 1).doOnCompleted(new Action0() {
          @Override
          public void call() {
            handler.post(new Runnable() {

              @Override
              public void run() {
                dismissLoading();
                setAdapter();

              }
            });

          }
        }).subscribe(new Action1<Void>() {

          @Override
          public void call(Void arg0) {
            // TODO Auto-generated method stub

          }
        });
  }

  /*
   * 下拉刷新
   */
  private class GetDataTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
      // HttpClient httpClient = new DefaultHttpClient();
      // HttpGet request = new HttpGet("");
      // HttpConnectionParams.setConnectionTimeout(request.getParams(), 10 *
      // 1000);
      // HttpConnectionParams.setSoTimeout(request.getParams(), 10 * 1000);
      // HttpConnectionParams.setTcpNoDelay(request.getParams(), true);
      // try {
      // xml = httpClient.execute(request, new BasicResponseHandler());
      // } catch (ClientProtocolException e) {
      // e.printStackTrace();
      // } catch (IOException e) {
      // e.printStackTrace();
      // }
      xml = "test";
      return xml;
    }

    @Override
    protected void onPostExecute(String result) {
      setAdapter();
      super.onPostExecute(result);
    }
  }

  private void setAdapter() {
    if (adapter == null) {
      adapter = new PrivateChannelRefreshAdapter(PrivatechannelActivity.this,
          mList, handler);
      adapter.setOnChangeCallback(this);
      listview.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
      pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
      pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
    if (adapter.getCount() == 0) {
      emptylayout.setVisibility(View.VISIBLE);
    } else {
      emptylayout.setVisibility(View.GONE);
    }
  }

  @Override
  public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
    if (handler != null) {
      handler.postDelayed(new Runnable() {

        @Override
        public void run() {
          new GetDataTask().execute();
        }
      }, 2000);
    }

  }

  @Override
  public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
    new GetDataTask().execute();
  }

  /**
   * 换一换
   */
  @Override
  public void onChangeClick(String key) {
    String subTags = "";
    if (channelKeyValueMap.get(key) != null
        && !channelKeyValueMap.get(key).isEmpty()) {
      for (String val : channelKeyValueMap.get(key)) {
        subTags += val + ";";
      }
    }

    // 获取对应大类下的子类内容
    if (Tools.isNotEmpty(subTags)) {
      subTags = subTags.substring(0, subTags.length() - 1);
      loadPrivateChannel(key, subTags);
    }

  }

  @Override
  protected void onDestroy() {
    if (mLeUser != null) {
      if (lastTags == null || !mLeUser.tags.equalsIgnoreCase(lastTags)) {
        LePreference.getInstance().save("interesttags", mLeUser.tags);
      }
    }

    if (channelMap != null) {
      channelMap = null;
    }

    if (selectedCategoryKey != null) {
      selectedCategoryKey.clear();
      selectedCategoryKey = null;
    }

    if (channelKeyValueMap != null) {
      channelKeyValueMap.clear();
      channelKeyValueMap = null;
    }

    if (mLePrivateChannelList != null) {
      if (mLePrivateChannelList.data != null) {
        mLePrivateChannelList.data.clear();
      }
      mLePrivateChannelList = null;
    }

    super.onDestroy();
  }
}
